#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDateTime>
#include <TaskManager.h>
#include <QMenu>
#include <AlgManager/imagestoragemanager.h>


// 在构造函数中添加系统托盘初始化
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_queryTimer(new QTimer(this))
    , m_trayIcon(nullptr)
    , m_trayMenu(nullptr)
    , m_isQuitting(false)
{
    ui->setupUi(this);

    setupUI();
    setupServices();
    loadDefaultParameters();
    updateParameterDisplay();

    setupQueryTimer();  // 设置定时查询

    // 初始化存储管理器
    ImageStorageManager::DeleteRule delete_rule;
    delete_rule.enabled = true;
    delete_rule.max_days = 7;
    delete_rule.max_total_size = 10LL * 1024 * 1024 * 1024; // 10GB

    ImageStorageManager::StorageRule storage_rule;
    storage_rule.enabled = true;
    storage_rule.storage_mode = ImageStorageManager::StorageRule::BOTH_MODES; // 共存模式

    ImageStorageManager::getInstance().initialize(
        "D:\\SaveData",
        delete_rule,
        storage_rule
        );

    // 创建系统托盘
    createTrayIcon();
    createTrayMenu();
    // 设置应用程序不在关闭最后一个窗口时退出
    QApplication::setQuitOnLastWindowClosed(false);

    SysLogManager::logInfo(InfoType::SYSTEM, "系统初始化完成");
}

// 修改析构函数，确保退出时清理托盘
MainWindow::~MainWindow()
{
    m_isQuitting = true; // 确保析构时标记为真正退出

    // 程序退出时关闭
    ImageStorageManager::getInstance().shutdown();
    // 先停止所有可能正在执行的操作
    if (m_queryTimer && m_queryTimer->isActive()) {
        m_queryTimer->stop();
    }

    if (m_deviceCommService) {
        delete m_deviceCommService;
    }

    // 停止算法服务（包含线程和动画）
    if (m_algorithmService) {
        delete m_algorithmService;
    }

    // 停止相机服务
    if (m_cameraService) {
        delete m_cameraService;
    }

    if (m_databaseService) {
        delete m_databaseService;
    }

    // 清理托盘相关资源
    if (m_trayIcon) {
        m_trayIcon->hide();
        delete m_trayIcon;
    }

    if (m_trayMenu) {
        delete m_trayMenu;
    }

    delete ui;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (!m_isQuitting) {
        // 不是真正退出，只是隐藏到托盘
        event->ignore();
        hide();

        // 确保托盘图标存在且可见
        if (!m_trayIcon && QSystemTrayIcon::isSystemTrayAvailable()) {
            createTrayIcon(); // 重新创建托盘图标
            createTrayMenu(); // 重新创建托盘菜单
        }

        if (m_trayIcon) {
            m_trayIcon->show(); // 确保托盘图标显示
            m_trayIcon->showMessage(
                "3D图像处理系统",
                "程序已最小化到系统托盘",
                QSystemTrayIcon::Information,
                2000
                );
        }

        SysLogManager::logInfo(InfoType::SYSTEM, "程序已最小化到系统托盘");
    } else {
        // 真正退出程序
        event->accept();
    }
}

void MainWindow::setupUI()
{
    // 设置窗口标题和大小
    setWindowTitle("3D图像处理系统 - 阴极板检测");
    resize(1200, 800);

    // 为图像显示区域设置布局
    QGridLayout *imageLayout = new QGridLayout(ui->widget);
    imageLayout->setContentsMargins(0, 0, 0, 0);
    imageLayout->setSpacing(0);

    // 创建 ImageWindow 并添加到布局
    m_imageWindow = new ImageWindow();
    m_imageWindow->setFitToWindow(true);
    imageLayout->addWidget(m_imageWindow);
    ui->widget->setLayout(imageLayout);

    // 初始化日志区域
    ui->textEditLog->setReadOnly(true);

    // 初始状态
    ui->btnPreProcess->setEnabled(false);
    ui->btnDefectDetection->setEnabled(false);
    ui->btnPathPlanning->setEnabled(false);
    ui->btnExecutePath->setEnabled(false);
    ui->btnAlgRunAll->setEnabled(false);

    // 查询按钮初始状态
    ui->btStartQuery->setEnabled(false);
    ui->btStartQuery->setText("开始定时查询");  // 修改按钮文本

    // 初始化夹具选择框
    setupFixtureComboBox();
}

void MainWindow::setupFixtureComboBox()
{
    // 清空现有的选项
    ui->comboBoxDO->clear();

    // 添加16个夹具选项
    for (int i = 1; i <= 16; i++) {
        ui->comboBoxDO->addItem(QString("夹具 %1").arg(i));
    }

    // 设置默认选择第一个夹具
    if (ui->comboBoxDO->count() > 0) {
        ui->comboBoxDO->setCurrentIndex(0);
    }
}

void MainWindow::setupServices()
{
    // 初始化各业务服务
    m_cameraService = new CameraService(m_imageWindow, this);
    m_algorithmService = new AlgorithmService(m_imageWindow, m_cameraService, this);  // 传递相机服务
    m_databaseService = new DatabaseService(this);
    m_deviceCommService = new DeviceCommService(this);

    // 获取任务管理器实例
    TaskManager& taskManager = TaskManager::instance();
    // 连接任务管理器信号到界面更新
    connect(&taskManager, &TaskManager::taskStarted,this, &MainWindow::onTaskReceived);


    // 连接日志信号
    connect(m_cameraService, &CameraService::logMessage, this, &MainWindow::onLogMessageReceived);
    connect(m_algorithmService, &AlgorithmService::logMessage, this, &MainWindow::onLogMessageReceived);
    connect(m_databaseService, &DatabaseService::logMessage, this, &MainWindow::onLogMessageReceived);
    connect(m_deviceCommService, &DeviceCommService::logMessage, this, &MainWindow::onLogMessageReceived);
    connect(&taskManager, &TaskManager::logMessage, this, &MainWindow::onLogMessageReceived);


    // 绑定日志信号
    connect(SysLogManager::getInstance(), &SysLogManager::logReceived,
            this, &MainWindow::onLogReceived);

    // 连接算法服务的结果更新信号
    connect(m_algorithmService, &AlgorithmService::resultsUpdated, this, &MainWindow::updateParameterDisplay);

    // 连接相机和算法的图像信号
    connect(m_cameraService, &CameraService::frameAcquired, m_algorithmService, &AlgorithmService::onFrameAcquired);

    // 连接数据库服务信号
    connect(m_databaseService, &DatabaseService::databaseConnected, this, [this](bool success, const QString& msg) {
        SysLogManager::logInfo(InfoType::DATABASE, msg);
        updateParameterDisplay();
    });

    // 启动数据库服务
    if (m_databaseService->initialize()) {
        // 启动任务轮询和状态监控
        m_databaseService->startTaskPolling(300);
        on_btnUpdateParameters_clicked();
        // m_databaseService->startStatusMonitoring(500);
    }

    SysLogManager::logInfo(InfoType::SYSTEM, "所有业务服务初始化完成");
    // 设置设备连接
    setupDeviceConnections();

    // 新增全自动执行信号连接
    setupAutoExecutionConnections();
}

void MainWindow::on_actionShowControl_triggered()
{
    ui->tabWidget->setCurrentIndex(0);
}

void MainWindow::on_actionShowResults_triggered()
{
    ui->tabWidget->setCurrentIndex(1);
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::about(this, "关于", "3D图像处理系统 - 阴极板检测\n\n基于Halcon和Qt开发");
}

void MainWindow::on_actionExit_triggered()
{
    onQuitApplication(); // 改为调用退出函数而不是直接close()
}

void MainWindow::onLogReceived(const QDateTime &time, int logType, int infoType, const QString &content)
{
    QString timeStr = time.toString("hh:mm:ss");
    QString typeStr = SysLogManager::logTypeToString(static_cast<LogType>(logType));
    QString infoStr = SysLogManager::infoTypeToString(static_cast<InfoType>(infoType));

    // 在界面上显示日志
    // ui->textEditLog->append(QString("[%1][%2][%3]: %4")
    //                             .arg(timeStr)
    //                             .arg(typeStr)
    //                             .arg(infoStr)
    //                             .arg(content));

    ui->textEditLog->append(QString("[%1]: %2")
                                .arg(timeStr)
                                .arg(content));
}

void MainWindow::onLogMessageReceived(const QString& message)
{
    SysLogManager::logInfo(InfoType::SYSTEM, message);
}

void MainWindow::updateParameterDisplay()
{
    // 更新按钮状态
    ui->btnSingleShot->setEnabled(m_cameraService->isCameraConnected());
    ui->btnPreProcess->setEnabled(m_algorithmService->hasImage());
    ui->btnDefectDetection->setEnabled(m_algorithmService->hasPreProcessResult());
    ui->btnPathPlanning->setEnabled(m_algorithmService->hasDefectResult());
    ui->btnExecutePath->setEnabled(m_algorithmService->hasPathResult());
    ui->btnAlgRunAll->setEnabled(m_algorithmService->hasImage()||m_cameraService->isCameraConnected());

    // 查询按钮状态
    ui->btStartQuery->setEnabled(m_connected);

    // 设备相关按钮状态
    ui->btnUploadCommand->setEnabled(m_connected && m_algorithmService->hasPathResult());
    ui->btnRunCommand->setEnabled(m_connected);
    ui->btnClearCommand->setEnabled(m_connected);
    ui->btnRegression->setEnabled(m_connected);
    ui->btnCommandRunAll->setEnabled(m_connected && m_algorithmService->hasPathResult());

    // 更新状态指示器
    updateStatusIndicators();
}

void MainWindow::updateStatusIndicators()
{
    // 更新图像状态指示器
    updateIndicatorStyle(ui->labelCurrentFile, m_algorithmService->hasImage());
    updateIndicatorStyle(ui->labelPreProcessTime, m_algorithmService->hasPreProcessResult());
    updateIndicatorStyle(ui->labelDefectTime, m_algorithmService->hasDefectResult());
    updateIndicatorStyle(ui->labelPathTime, m_algorithmService->hasPathResult());



    // 更新服务状态指示器
    QString statusText = QString("相机: %1 | 数据库: %2 | 设备: %3")
                             .arg(m_cameraService->getCameraStatus(), m_databaseService->getConnectionStatus(), m_deviceCommService->getConnectionStatus());

    ui->statusbar->showMessage(statusText);

    // 更新状态文本
    if (m_algorithmService->hasImage()) {
        auto image = m_algorithmService->getCurrentImage();
        try {
            HTuple width, height;
            if (image.Gray.IsInitialized()) {
                GetImageSize(image.Gray, &width, &height);
                ui->labelCurrentFile->setText(QString("图像ID: %1, 尺寸: %2x%3").arg(image.ID).arg(width.I()).arg(height.I()));
            }
        } catch (...) {
            ui->labelCurrentFile->setText(QString("图像ID: %1").arg(image.ID));
        }
    } else {
        ui->labelCurrentFile->setText("未加载图像");
    }

    // 更新时间显示
    auto preProcessResult = m_algorithmService->getPreProcessResult();
    auto defectResult = m_algorithmService->getDefectResult();
    auto pathResult = m_algorithmService->getPathResult();

    ui->labelPreProcessTime->setText(QString::number(preProcessResult.time, 'f', 3) + " s");
    ui->labelDefectTime->setText(QString::number(defectResult.time, 'f', 3) + " s");
    ui->labelPathTime->setText(QString::number(pathResult.time, 'f', 3) + " s");



    // 更新路径点统计
    if (m_algorithmService->hasPathResult()) {
        auto pathResult = m_algorithmService->getPathResult();
        ui->labelTotalPoints->setText(QString::number(pathResult.iNumPts));

        int startPoints = 0, endPoints = 0, wayPoints = 0, airPoints = 0;
        for (const auto &point : pathResult.sListPPtsRobot) {
            switch (point.iDef) {
            case 1: startPoints++; break;
            case 2: endPoints++; break;
            case 3: wayPoints++; break;
            case 4: airPoints++; break;
            }
        }

        ui->labelStartPoints->setText(QString::number(startPoints));
        ui->labelEndPoints->setText(QString::number(endPoints));
        ui->labelWayPoints->setText(QString::number(wayPoints));
        ui->labelAirPoints->setText(QString::number(airPoints));
    } else {
        ui->labelTotalPoints->setText("0");
        ui->labelStartPoints->setText("0");
        ui->labelEndPoints->setText("0");
        ui->labelWayPoints->setText("0");
        ui->labelAirPoints->setText("0");
    }
}

void MainWindow::updateIndicatorStyle(QLabel *label, bool status)
{
    if (status) {
        label->setStyleSheet("QLabel { "
                             "background-color: #90EE90; "
                             "border: 1px solid #006400; "
                             "padding: 2px; "
                             "border-radius: 3px; "
                             "color: #006400; "
                             "font-weight: bold; "
                             "}");
    } else {
        label->setStyleSheet("QLabel { "
                             "background-color: #FFB6C1; "
                             "border: 1px solid #8B0000; "
                             "padding: 2px; "
                             "border-radius: 3px; "
                             "color: #8B0000; "
                             "font-weight: bold; "
                             "}");
    }
}

void MainWindow::loadDefaultParameters()
{
    SysEnv& env = SysEnv::instance();

    // 直接使用DataX.h中的数据结构
    const s_PreProcess3DSPara& prePara = env.cfg().preProcessPara;
    const s_DefectPlateBPara& defectPara = env.cfg().defectPara;
    const s_JggyPara& pathPara = env.cfg().pathPara;
    const s_PoseH& posePara  = env.cfg().cameraToRobotPose;
    // ==== 获取工艺参数 ====
    const ProcessParams& processPara = env.cfg().processParams;

    // 设置预处理参数
    ui->spinRoiZMin->setValue(prePara.fRoiZMin);
    ui->spinRoiZMax->setValue(prePara.fRoiZMax);
    ui->spinRoiXMin->setValue(prePara.fRoiXMin);
    ui->spinRoiXMax->setValue(prePara.fRoiXMax);
    ui->spinRoiYMin->setValue(prePara.fRoiYMin);
    ui->spinRoiYMax->setValue(prePara.fRoiYMax);
    ui->spinSegDis->setValue(prePara.fThSeg0Dis);
    ui->spinSegNumMin->setValue(prePara.iThSeg0NumPtsMin);
    ui->spinSegNumMax->setValue(prePara.iThSeg0NumPtsMax);
    ui->spinSegDiaMin->setValue(prePara.fThSeg0DiameterMin);
    ui->spinSegDiaMax->setValue(prePara.fThSeg0DiameterMax);

    // 设置缺陷检测参数
    ui->spinThNZAbsVal->setValue(defectPara.fThNZAbsVal);
    ui->spinQgOffsetL->setValue(defectPara.fQgOffsetL);
    ui->spinQgOffsetR->setValue(defectPara.fQgOffsetR);
    ui->spinQgOffsetU->setValue(defectPara.fQgOffsetU);
    ui->spinQgOffsetD->setValue(defectPara.fQgOffsetD);

    // 凸起阈值参数
    ui->spinThBulgeLowerC->setValue(defectPara.fThBulgeLowerC);
    ui->spinThBulgeHigerC->setValue(defectPara.fThBulgeHigerC);
    ui->spinThBulgeLowerS->setValue(defectPara.fThBulgeLowerS);
    ui->spinThBulgeHigerS->setValue(defectPara.fThBulgeHigerS);

    ui->spinQgThOffset->setValue(defectPara.fQgThOffset);

    // 气缸参数
    ui->spinQgLHOrg->setValue(defectPara.fQgLHOrg);
    ui->spinQgLExCol->setValue(defectPara.fQgLExCol);
    ui->spinQgLExRow->setValue(defectPara.fQgLExRow);

    ui->spinQgRHOrg->setValue(defectPara.fQgRHOrg);
    ui->spinQgRExCol->setValue(defectPara.fQgRExCol);
    ui->spinQgRExRow->setValue(defectPara.fQgRExRow);

    ui->spinQgUHOrg->setValue(defectPara.fQgUHOrg);
    ui->spinQgUExCol->setValue(defectPara.fQgUExCol);
    ui->spinQgUExRow->setValue(defectPara.fQgUExRow);

    ui->spinQgDHOrg->setValue(defectPara.fQgDHOrg);
    ui->spinQgDExCol->setValue(defectPara.fQgDExCol);
    ui->spinQgDExRow->setValue(defectPara.fQgDExRow);

    ui->spinConnectionDis->setValue(defectPara.fConnectionDis);

    // 设置路径规划参数
    ui->spinDjDiamiter->setValue(pathPara.fDjDiamiter);
    ui->spinJgLzUpOffset->setValue(pathPara.fJgLzUpOffset);
    ui->spinJgDpUpOffset->setValue(pathPara.fJgDpUpOffset);
    ui->comiModeJgPPZStepMode->setCurrentIndex(pathPara.iModeJgPPZStepMode);
    ui->spinJgPPZStepFix->setValue(pathPara.fJgPPZStepFix);
    ui->spinJgPPZStepK->setValue(pathPara.fJgPPZStepK);
    ui->spinJgPPZStepB->setValue(pathPara.fJgPPZStepB);

    ui->spinJgPPZStepMin->setValue(pathPara.fJgPPZStepMin);
    ui->spinJgPPZStepMax->setValue(pathPara.fJgPPZStepMax);

    ui->comiModeJgPPYStepMode->setCurrentIndex(pathPara.iModeJgPPYStepMode);
    ui->spinJgPPYStepFix->setValue(pathPara.fJgPPYStepFix);
    ui->spinJgPPYStepK->setValue(pathPara.fJgPPYStepK);
    ui->comiModeJgPPSort->setCurrentIndex(pathPara.iModeJgPPSort);
    ui->spinQgSafeDis->setValue(pathPara.fQgSafeDis);

    ui->spinJgTdZUp->setValue(pathPara.fJgTdZUp);

    ui->spinOffsetCutStartPos->setValue(pathPara.fOffsetCutStartPos);
    ui->spinOffsetBothEndsL->setValue(pathPara.fOffsetBothEndsL);
    ui->spinOffsetBothEndsR->setValue(pathPara.fOffsetBothEndsR);

    ui->spinOffsetPtsX->setValue(pathPara.fOffsetPtsX);
    ui->spinOffsetPtsY->setValue(pathPara.fOffsetPtsY);
    ui->spinOffsetPtsZ->setValue(pathPara.fOffsetPtsZ);


    ui->spinCamRobotTransX->setValue(posePara.fTransX);
    ui->spinCamRobotTransY->setValue(posePara.fTransY);
    ui->spinCamRobotTransZ->setValue(posePara.fTransZ);
    ui->spinCamRobotRotX->setValue(posePara.fRotX);
    ui->spinCamRobotRotY->setValue(posePara.fRotY);
    ui->spinCamRobotRotZ->setValue(posePara.fRotZ);
    ui->spinCamRobotdwType->setValue(posePara.dwType);

    // 设置工艺参数 ====
    ui->lineEdit_RapidRate->setText(QString::number(processPara.rapidSpeed));
    ui->lineEdit_FeedRate->setText(QString::number(processPara.feedRate));
    ui->lineEdit_SpindleSpeed->setText(QString::number(processPara.toolSpeed));
    ui->lineEdit_ToolDiameter->setText(QString::number(processPara.toolDiameter));
    ui->lineEdit_LineSpacing->setText(QString::number(processPara.lineSpacing));
    ui->lineEdit_CuttingDepth->setText(QString::number(processPara.cuttingDepth));
    ui->lineEdit_WorkpieceHeight->setText(QString::number(processPara.workpieceSurfaceHeight));
    ui->lineEdit_TotalCuttingDepth->setText(QString::number(processPara.totalCuttingDepth));
    ui->lineEdit_StepDistance->setText(QString::number(processPara.stepDistance));
    ui->lineEdit_JogSpeed->setText(QString::number(processPara.jogSpeed));

    SysLogManager::logInfo(InfoType::SYSTEM, "默认参数加载完成");
}

void MainWindow::saveParameters()
{
    SysEnv& env = SysEnv::instance();

    // 预处理参数
    env.cfg().preProcessPara.fRoiZMin = ui->spinRoiZMin->value();
    env.cfg().preProcessPara.fRoiZMax = ui->spinRoiZMax->value();
    env.cfg().preProcessPara.fRoiXMin = ui->spinRoiXMin->value();
    env.cfg().preProcessPara.fRoiXMax = ui->spinRoiXMax->value();
    env.cfg().preProcessPara.fRoiYMin = ui->spinRoiYMin->value();
    env.cfg().preProcessPara.fRoiYMax = ui->spinRoiYMax->value();
    env.cfg().preProcessPara.fThSeg0Dis = ui->spinSegDis->value();
    env.cfg().preProcessPara.iThSeg0NumPtsMin = ui->spinSegNumMin->value();
    env.cfg().preProcessPara.iThSeg0NumPtsMax = ui->spinSegNumMax->value();
    env.cfg().preProcessPara.fThSeg0DiameterMin = ui->spinSegDiaMin->value();
    env.cfg().preProcessPara.fThSeg0DiameterMax = ui->spinSegDiaMax->value();

    // 缺陷检测参数
    env.cfg().defectPara.fThNZAbsVal = ui->spinThNZAbsVal->value();
    env.cfg().defectPara.fQgOffsetL = ui->spinQgOffsetL->value();
    env.cfg().defectPara.fQgOffsetR = ui->spinQgOffsetR->value();
    env.cfg().defectPara.fQgOffsetU = ui->spinQgOffsetU->value();
    env.cfg().defectPara.fQgOffsetD = ui->spinQgOffsetD->value();

    // 凸起阈值参数
    env.cfg().defectPara.fThBulgeLowerC = ui->spinThBulgeLowerC->value();
    env.cfg().defectPara.fThBulgeHigerC = ui->spinThBulgeHigerC->value();
    env.cfg().defectPara.fThBulgeLowerS = ui->spinThBulgeLowerS->value();
    env.cfg().defectPara.fThBulgeHigerS = ui->spinThBulgeHigerS->value();

    env.cfg().defectPara.fQgThOffset = ui->spinQgThOffset->value();

    // 气缸参数
    env.cfg().defectPara.fQgLHOrg = ui->spinQgLHOrg->value();
    env.cfg().defectPara.fQgLExCol = ui->spinQgLExCol->value();
    env.cfg().defectPara.fQgLExRow = ui->spinQgLExRow->value();

    env.cfg().defectPara.fQgRHOrg = ui->spinQgRHOrg->value();
    env.cfg().defectPara.fQgRExCol = ui->spinQgRExCol->value();
    env.cfg().defectPara.fQgRExRow = ui->spinQgRExRow->value();

    env.cfg().defectPara.fQgUHOrg = ui->spinQgUHOrg->value();
    env.cfg().defectPara.fQgUExCol = ui->spinQgUExCol->value();
    env.cfg().defectPara.fQgUExRow = ui->spinQgUExRow->value();

    env.cfg().defectPara.fQgDHOrg = ui->spinQgDHOrg->value();
    env.cfg().defectPara.fQgDExCol = ui->spinQgDExCol->value();
    env.cfg().defectPara.fQgDExRow = ui->spinQgDExRow->value();

    env.cfg().defectPara.fConnectionDis = ui->spinConnectionDis->value();

    // 路径规划参数
    env.cfg().pathPara.fDjDiamiter = ui->spinDjDiamiter->value();
    env.cfg().pathPara.fJgLzUpOffset = ui->spinJgLzUpOffset->value();
    env.cfg().pathPara.fJgDpUpOffset = ui->spinJgDpUpOffset->value();
    env.cfg().pathPara.fQgSafeDis = ui->spinQgSafeDis->value();
    env.cfg().pathPara.fJgTdZUp = ui->spinJgTdZUp->value();
    env.cfg().pathPara.iModeJgPPZStepMode = ui->comiModeJgPPZStepMode->currentIndex();
    env.cfg().pathPara.fJgPPZStepFix = ui->spinJgPPZStepFix->value();
    env.cfg().pathPara.fJgPPZStepK = ui->spinJgPPZStepK->value();
    env.cfg().pathPara.fJgPPZStepB = ui->spinJgPPZStepB->value();
    env.cfg().pathPara.fJgPPZStepMin = ui->spinJgPPZStepMin->value();
    env.cfg().pathPara.fJgPPZStepMax = ui->spinJgPPZStepMax->value();
    env.cfg().pathPara.iModeJgPPSort = ui->comiModeJgPPSort->currentIndex();
    env.cfg().pathPara.fJgPPYStepK = ui->spinJgPPYStepK->value();
    env.cfg().pathPara.fOffsetCutStartPos = ui->spinOffsetCutStartPos->value();
    env.cfg().pathPara.fOffsetBothEndsL = ui->spinOffsetBothEndsL->value();
    env.cfg().pathPara.fOffsetBothEndsR = ui->spinOffsetBothEndsR->value();
    env.cfg().pathPara.fOffsetPtsX = ui->spinOffsetPtsX->value();
    env.cfg().pathPara.fOffsetPtsY = ui->spinOffsetPtsY->value();
    env.cfg().pathPara.fOffsetPtsZ = ui->spinOffsetPtsZ->value();


    env.cfg().cameraToRobotPose.fTransX = ui->spinCamRobotTransX->value();
    env.cfg().cameraToRobotPose.fTransY = ui->spinCamRobotTransY->value();
    env.cfg().cameraToRobotPose.fTransZ = ui->spinCamRobotTransZ->value();
    env.cfg().cameraToRobotPose.fRotX = ui->spinCamRobotRotX->value();
    env.cfg().cameraToRobotPose.fRotY = ui->spinCamRobotRotY->value();
    env.cfg().cameraToRobotPose.fRotZ = ui->spinCamRobotRotZ->value();
    env.cfg().cameraToRobotPose.dwType = ui->spinCamRobotdwType->value();


    // ==== 保存工艺参数 ====
    env.cfg().processParams.rapidSpeed = ui->lineEdit_RapidRate->text().toDouble();
    env.cfg().processParams.feedRate = ui->lineEdit_FeedRate->text().toDouble();
    env.cfg().processParams.toolSpeed = ui->lineEdit_SpindleSpeed->text().toDouble();
    env.cfg().processParams.toolDiameter = ui->lineEdit_ToolDiameter->text().toDouble();
    env.cfg().processParams.lineSpacing = ui->lineEdit_LineSpacing->text().toDouble();
    env.cfg().processParams.cuttingDepth = ui->lineEdit_CuttingDepth->text().toDouble();
    env.cfg().processParams.workpieceSurfaceHeight = ui->lineEdit_WorkpieceHeight->text().toDouble();
    env.cfg().processParams.totalCuttingDepth = ui->lineEdit_TotalCuttingDepth->text().toDouble();
    env.cfg().processParams.stepDistance = ui->lineEdit_StepDistance->text().toDouble();
    env.cfg().processParams.jogSpeed = ui->lineEdit_JogSpeed->text().toDouble();

    env.save();
}

void MainWindow::logMessage(const QString& message)
{
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
    ui->textEditLog->append(QString("[%1] %2").arg(timestamp, message));
    // 延迟更新，避免递归
    QTimer::singleShot(0, this, &MainWindow::updateParameterDisplay);
}


void MainWindow::setupQueryTimer()
{
    // 连接定时器超时信号
    connect(m_queryTimer, &QTimer::timeout, this, &MainWindow::onQueryTimeout);

    // 设置定时器为单次触发，在每次查询完成后重新启动
    m_queryTimer->setSingleShot(true);
}

void MainWindow::setupAutoExecutionConnections()
{
    connect(m_deviceCommService, &DeviceCommService::autoExecutionStarted,
            this, &MainWindow::onAutoExecutionStarted);
    connect(m_deviceCommService, &DeviceCommService::autoExecutionProgress,
            this, &MainWindow::onAutoExecutionProgress);
    connect(m_deviceCommService, &DeviceCommService::autoExecutionStopped,
            this, &MainWindow::onAutoExecutionStopped);
    connect(m_deviceCommService, &DeviceCommService::autoExecutionFinished,
            this, &MainWindow::onAutoExecutionFinished);
}

void MainWindow::on_btnAutoExecuteAll_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "设备未连接，无法执行全自动流程");
        TaskManager::instance().completeTaskStatus(TaskType::RUN_START,false,"设备未连接");
        return;
    }

    if (!m_algorithmService->hasPathResult()) {
        SysLogManager::logError(InfoType::PATH_PLANNING, "请先生成路径规划");
        TaskManager::instance().completeTaskStatus(TaskType::RUN_START,false,"路径规划未生成");
        return;
    }

    auto commandGroups = m_algorithmService->getCommandGroups();
    if (commandGroups.isEmpty()) {
        SysLogManager::logError(InfoType::COMMAND_EXEC, "没有可执行的指令组");
        TaskManager::instance().completeTaskStatus(TaskType::RUN_START,false,"没有可执行的指令组");
        return;
    }

    SysLogManager::logInfo(InfoType::COMMAND_EXEC, QString("🚀 开始全自动执行 %1 组指令...").arg(commandGroups.size()));

    // 设置分组指令
    m_deviceCommService->setCommandGroups(commandGroups);

    // 开始全自动执行
    m_deviceCommService->executeAllGroupsAutomatically();
}

void MainWindow::on_btnStopAutoExecution_clicked()
{
    if (m_deviceCommService->isAutoExecuting()) {
        m_deviceCommService->stopAutoExecution();
    }
}

void MainWindow::onAutoExecutionStarted()
{
    SysLogManager::logInfo(InfoType::COMMAND_EXEC, "🚀 全自动执行已开始");
    setAutoExecutionUIState(true);
}

void MainWindow::onAutoExecutionProgress(int currentGroup, int totalGroups, const QString &status)
{
    int progress = (currentGroup * 100) / totalGroups;
    QString progressText = QString("全自动进度: %1/%2 (%3%) - %4")
                               .arg(currentGroup)
                               .arg(totalGroups)
                               .arg(progress)
                               .arg(status);

    SysLogManager::logInfo(InfoType::COMMAND_EXEC, progressText);

    // 更新进度条或状态显示
    ui->statusbar->showMessage(progressText);
}

void MainWindow::onAutoExecutionFinished(bool success, const QString &message)
{
    setAutoExecutionUIState(false);

    if (success) {
        SysLogManager::logSuccess(InfoType::COMMAND_EXEC, "🎉 " + message);
    } else {
        SysLogManager::logError(InfoType::COMMAND_EXEC, "❌ " + message);
    }

    ui->statusbar->showMessage("全自动执行完成");
    on_btnUnloadMaterial_clicked();
}

void MainWindow::onAutoExecutionStopped()
{
    setAutoExecutionUIState(false);
    SysLogManager::logWarning(InfoType::COMMAND_EXEC, "⏹️ 全自动执行已停止");
}

void MainWindow::setAutoExecutionUIState(bool executing)
{
    ui->btnAutoExecuteAll->setEnabled(!executing);
    ui->btnStopAutoExecution->setEnabled(executing);
    ui->btnUploadCommand->setEnabled(!executing);
    ui->btnRunCommand->setEnabled(!executing);
    ui->btnCommandRunAll->setEnabled(!executing);
    ui->btnRegression->setEnabled(!executing);
    ui->btnClearCommand->setEnabled(!executing);

    if (executing) {
        ui->btnAutoExecuteAll->setText("执行中...");
    } else {
        ui->btnAutoExecuteAll->setText("全自动执行所有组");
    }
}


// 图像本地加载
void MainWindow::on_btnLoadImage_clicked()
{

    QString filePath = QFileDialog::getOpenFileName(this, "选择3D图像灰度文件", "", "Image Files (*.png);;All Files (*.*)");
    if (!filePath.isEmpty()) {
        m_algorithmService->load3DImage(filePath);
    }
}

// 单帧采集图像
void MainWindow::on_btnSingleShot_clicked()
{
    m_cameraService->triggerSingleShot();
}

// 预处理
void MainWindow::on_btnPreProcess_clicked()
{
    m_algorithmService->preProcess();
}

// 缺陷处理
void MainWindow::on_btnDefectDetection_clicked()
{
    m_algorithmService->defectDetection();
}

// 路径规划
void MainWindow::on_btnPathPlanning_clicked()
{
    m_algorithmService->pathPlanning();

}

void MainWindow::on_btnAlgRunAll_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "设备未连接，无法执行全流程");
        TaskManager::instance().completeTaskStatus(TaskType::CAPTURE,false,"设备未连接，无法执行全流程");
        return;
    }

    SysLogManager::logInfo(InfoType::SYSTEM, "🔄 开始全流程执行：上料检查 → 图像处理");

    // 先执行上料
    on_btnLoadMaterial_clicked();

    // 启动状态监控，等待上料完成
    startLoadMaterialMonitoring();
}

void MainWindow::startLoadMaterialMonitoring()
{
    m_loadMaterialTimer = new QTimer(this);
    m_loadMaterialTimer->setSingleShot(false);
    m_loadMaterialCheckCount = 0;
    const int MAX_CHECK_COUNT = 30; // 最大检查30次（30秒）
    const int CHECK_INTERVAL = 500; // 500毫秒检查一次

    connect(m_loadMaterialTimer, &QTimer::timeout, this, [this, MAX_CHECK_COUNT]() {
        m_loadMaterialCheckCount++;

        // 获取当前夹具状态
        StatusTable currentStatus;
        m_deviceCommService->getCurrentStatus(currentStatus);
        QString fixtureStatus = currentStatus.fixtureStatus;

        SysLogManager::logInfo(InfoType::DEVICE, QString("📋 上料状态检查 %1/%2: %3")
                                                     .arg(m_loadMaterialCheckCount)
                                                     .arg(MAX_CHECK_COUNT)
                                                     .arg(getFixtureStatusText(fixtureStatus)));

        // 检查是否所有夹具都已夹紧
        if (isAllFixturesClamped(fixtureStatus)) {
            m_loadMaterialTimer->stop();
            m_loadMaterialTimer->deleteLater();
            m_loadMaterialTimer = nullptr;

            SysLogManager::logSuccess(InfoType::DEVICE, "✅ 上料完成，所有夹具已夹紧，开始图像处理");
            // 上料完成，执行图像处理
            QTimer::singleShot(500, this, [this]() {
                m_algorithmService->runAllProcessing();
            });
            return;
        }

        // 超时检查
        if (m_loadMaterialCheckCount >= MAX_CHECK_COUNT) {
            m_loadMaterialTimer->stop();
            m_loadMaterialTimer->deleteLater();
            m_loadMaterialTimer = nullptr;

            SysLogManager::logError(InfoType::DEVICE, "❌ 上料超时，无法确认夹具状态，停止流程");
            QMessageBox::warning(this, "上料超时", "夹具夹紧操作超时，请手动检查设备状态");
        } else {
            // 继续查询状态
            m_deviceCommService->queryDIStatus();
        }
    });

    // 启动定时器
    m_loadMaterialTimer->start(CHECK_INTERVAL);
    // 立即执行一次查询
    m_deviceCommService->queryDIStatus();
}

// 路径本地执行
void MainWindow::on_btnExecutePath_clicked()
{
    m_algorithmService->executePathAnimation();
}

/* 先获取路径规划的结果 再进行解析转化指令*/
//上传全部指令
void MainWindow::on_btnUploadCommand_clicked()
{
    // 获取算法服务生成的指令
    m_deviceCommService->setCommands(m_algorithmService->getPathCommands());
    m_deviceCommService->uploadAllCommands();
}

//运行指令
void MainWindow::on_btnRunCommand_clicked()
{
    m_deviceCommService->startExecute();
}

// 清除并初始化
void MainWindow::on_btnClearCommand_clicked()
{
    m_deviceCommService->clearAction();
}

// 回归零位
void MainWindow::on_btnRegression_clicked()
{
    m_deviceCommService->RegressionAction();
}

// 指令处理全流程
void MainWindow::on_btnCommandRunAll_clicked()
{
    // 获取算法服务生成的指令
    m_deviceCommService->setCommands(m_algorithmService->getPathCommands());
    m_deviceCommService->executeCommandsProcessing();
}


void MainWindow::on_btnClearLog_clicked()
{
    ui->textEditLog->clear();
    SysLogManager::logInfo(InfoType::SYSTEM, "日志已清空");
}

void MainWindow::on_Bt_save_clicked()
{
    saveParameters();
    SysLogManager::logInfo(InfoType::SYSTEM, "参数已保存");
}


void MainWindow::onTaskReceived(const HardwareTaskQueue& task) {
    SysLogManager::logInfo(InfoType::SYSTEM, QString("收到任务 #%1: %2 (类型: %3)")
                                                 .arg(task.id)
                                                 .arg(task.task_name)
                                                 .arg(static_cast<int>(task.task_type)));

    processTask(task);
}

void MainWindow::onTaskProcessed(const TaskExecutionResult& result) {
    // 可以在这里处理任务完成后的统一逻辑
    SysLogManager::logInfo(InfoType::SYSTEM, QString("任务 #%1 处理完成: %2")
                                                 .arg(result.taskId)
                                                 .arg(result.message));
}

// 托盘图标激活处理
void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::DoubleClick:
    case QSystemTrayIcon::Trigger:
        onShowMainWindow();
        break;
    default:
        break;
    }
}

// 显示主窗口
void MainWindow::onShowMainWindow()
{
    show();
    raise();
    activateWindow();

    if (m_trayIcon) {
        m_trayIcon->hide(); // 可选：显示主窗口时隐藏托盘消息
    }
}

void MainWindow::onQuitApplication()
{
    m_isQuitting = true; // 标记为真正退出

    SysLogManager::logInfo(InfoType::SYSTEM, "正在退出应用程序...");

    // 隐藏托盘图标
    if (m_trayIcon) {
        m_trayIcon->hide();
    }

    // 关闭主窗口，这会触发closeEvent
    close();

    // 确保应用程序退出
    QApplication::quit();
}

void MainWindow::processTask(const HardwareTaskQueue& task) {
    TaskManager& taskManager = TaskManager::instance();
    try {//任务开关
        switch (task.task_type) {
        case TaskType::CAPTURE:
        case TaskType::RUN_START:
        case TaskType::MANUAL_SINGLE_FRAME_CAPTURE:
        case TaskType::MANUAL_PREPROCESS_ROI_CLUSTER:
        case TaskType::MANUAL_DEFECT_DETECTION:
        case TaskType::MANUAL_DEFECT_DETECTION_SECONDARY:
        case TaskType::MANUAL_C5_UPLOAD:
        case TaskType::MANUAL_RUN_COMMAND:
        case TaskType::MANUAL_CLEAR_UPLOAD:
        case TaskType::MANUAL_INITIALIZE:
        case TaskType::UPDATE_PARAMETERS:
            executeTask(task);
            break;
        default:
            taskManager.completeTaskStatus(task.task_type,false,QString("未知任务类型: %1").arg(static_cast<int>(task.task_type)));
            break;
        }
    } catch (const std::exception& e) {
        taskManager.completeTaskStatus(task.task_type,false,QString("任务执行异常: %1").arg(e.what()));
    }
}

void MainWindow::executeTask(const HardwareTaskQueue& task) {
    // 处理任务
    switch (task.task_type) {//全流程采集
    case TaskType::UPDATE_PARAMETERS:
        on_btnUpdateParameters_clicked();
        break;
    case TaskType::CAPTURE:
        on_btnAlgRunAll_clicked();
        break;
    case TaskType::RUN_START:
        on_btnAutoExecuteAll_clicked();
        break;
    case TaskType::MANUAL_SINGLE_FRAME_CAPTURE:
        m_cameraService->triggerSingleShot();
        break;
    case TaskType::MANUAL_PREPROCESS_ROI_CLUSTER:
        m_algorithmService->preProcess();
        break;
    case TaskType::MANUAL_DEFECT_DETECTION:
        m_algorithmService->defectDetection();
        break;
    case TaskType::MANUAL_DEFECT_DETECTION_SECONDARY:
        m_algorithmService->pathPlanning();
        break;
    case TaskType::MANUAL_C5_UPLOAD:
        m_deviceCommService->setCommands(m_algorithmService->getPathCommands());
        m_deviceCommService->uploadAllCommands();
        break;
    case TaskType::MANUAL_RUN_COMMAND:
        m_deviceCommService->startExecute();
        break;
    case TaskType::MANUAL_CLEAR_UPLOAD:
        m_deviceCommService->clearAction();
        break;
    case TaskType::MANUAL_INITIALIZE:
    case TaskType::MANUAL_INITIALIZE_SECONDARY:
        m_deviceCommService->clearAction();
        break;
    case TaskType::LOAD_MATERIAL:
        on_btnLoadMaterial_clicked();
        break;
    case TaskType::UNLOAD_MATERIAL:
        on_btnUnloadMaterial_clicked();
        break;
    default:
        break;
    }
}

QVariantMap MainWindow::parseTaskParams(const QJsonObject& taskParams) {
    QVariantMap params;
    for (auto it = taskParams.begin(); it != taskParams.end(); ++it) {
        params[it.key()] = it.value().toVariant();
    }
    return params;
}

// 解析夹具状态并生成带符号的描述文本
QString MainWindow::getFixtureStatusText(const QString& fixtureStatus)
{
    if (fixtureStatus.isEmpty()) {
        return "夹具状态: <span style='color:gray;'>未知</span>";
    }

    // 将16进制字符串转换为数值
    bool ok;
    quint32 fixtureBits = fixtureStatus.toUInt(&ok, 16);
    if (!ok) {
        return "夹具状态: <span style='color:red;'>格式错误</span>";
    }

    QStringList fixtureList;

    // 根据协议附录B的IO设备编址解析夹具状态
    const quint32 fixtureMasks[16] = {
        0x00001,  // 夹具1
        0x00002,  // 夹具2
        0x00004,  // 夹具3
        0x00008,  // 夹具4
        0x00010,  // 夹具5
        0x00020,  // 夹具6
        0x00040,  // 夹具7
        0x00080,  // 夹具8
        0x00100,  // 夹具9
        0x00200,  // 夹具10
        0x00400,  // 夹具11
        0x00800,  // 夹具12
        0x01000,  // 夹具13
        0x02000,  // 夹具14
        0x04000,  // 夹具15
        0x08000   // 夹具16
    };

    for (int i = 0; i < 16; i++) {
        bool isClamped = (fixtureBits & fixtureMasks[i]) != 0;
        QString symbol = isClamped ? "○" : "●";
        QString color = isClamped ? "red" : "green";
        QString status = isClamped ? "松开" : "夹紧";

        fixtureList.append(QString("<span style='color:%1;'>%2%3:%4</span>")
                               .arg(color).arg(symbol).arg(i + 1).arg(status));
    }

    // 检查特殊状态
    if (fixtureBits == 0x00000) {
        return "夹具状态: <span style='color:green;'>●全部夹紧</span>";
    } else if (fixtureBits == 0x0FFFF) {
        return "夹具状态: <span style='color:red;'>○全部松开</span>";
    } else {
        return "夹具: " + fixtureList.join(" ");
    }
}

void MainWindow::createTrayIcon()
{
    if (QSystemTrayIcon::isSystemTrayAvailable()) {
        // 如果已经存在，先清理再创建
        if (m_trayIcon) {
            m_trayIcon->hide();
            delete m_trayIcon;
            m_trayIcon = nullptr;
        }

        m_trayIcon = new QSystemTrayIcon(this);

        // 设置图标
        QIcon appIcon = QApplication::windowIcon();
        if (appIcon.isNull()) {
            appIcon = style()->standardIcon(QStyle::SP_ComputerIcon);
        }
        m_trayIcon->setIcon(appIcon);

        m_trayIcon->setToolTip("3D图像处理系统 - 阴极板检测");
        connect(m_trayIcon, &QSystemTrayIcon::activated,
                this, &MainWindow::onTrayIconActivated);

        m_trayIcon->show();
    }
}

void MainWindow::createTrayMenu()
{
    if (m_trayIcon) {
        m_trayMenu = new QMenu(this);

        QAction *showAction = m_trayMenu->addAction("显示主窗口");
        QAction *quitAction = m_trayMenu->addAction("退出");

        connect(showAction, &QAction::triggered, this, &MainWindow::onShowMainWindow);
        connect(quitAction, &QAction::triggered, this, &MainWindow::onQuitApplication);

        m_trayIcon->setContextMenu(m_trayMenu);
    }
}

// 开始定时查询
void MainWindow::startPeriodicQuery()
{
    m_queryEnabled = true;
    m_queryTimer->start(m_queryInterval);

    ui->btStartQuery->setText("停止定时查询");
    ui->btStartQuery->setStyleSheet("QPushButton { background-color: #ff6b6b; color: white; }"); // 红色停止按钮

    SysLogManager::logSuccess(InfoType::DEVICE, QString("✅ 启动定时查询，间隔: %1ms").arg(m_queryInterval));

    // 立即执行一次查询
    executeSingleQuery();
}

// 停止定时查询
void MainWindow::stopPeriodicQuery()
{
    m_queryEnabled = false;
    m_queryTimer->stop();

    ui->btStartQuery->setText("开始定时查询");
    ui->btStartQuery->setStyleSheet(""); // 恢复默认样式

    SysLogManager::logWarning(InfoType::DEVICE, "⏹️ 停止定时查询");

    // 清除状态栏中的设备状态信息
    QString currentStatusText = ui->statusbar->currentMessage();
    if (currentStatusText.contains("| 设备状态:")) {
        int deviceStatusStart = currentStatusText.indexOf("| 设备状态:");
        ui->statusbar->showMessage(currentStatusText.left(deviceStatusStart));
    }
}

// 执行单次查询
void MainWindow::executeSingleQuery()
{
    if (!m_connected) {
        return;
    }
    StatusTable currentStatus;
    m_deviceCommService->getCurrentStatus(currentStatus);

    // 更新夹具状态显示
    QString fixtureText = getFixtureStatusText(currentStatus.fixtureStatus);
    ui->textDI->setTextFormat(Qt::RichText);  // 启用富文本显示
    ui->textDI->setText(fixtureText);


    // 在状态栏显示关键状态信息
    QString statusInfo = QString("设备状态: %1 | 模式: %2 | 报警: %3")
                             .arg(currentStatus.getRunStatusText())
                             .arg(currentStatus.getControlModeText())
                             .arg(currentStatus.getAlarmStatusText());

    ui->textState->setText(statusInfo);


    QString strAbsolutePosition = QString("绝对坐标: x: %1 | y: %2 | z: %3")
                                      .arg(currentStatus.absolutePosition.x)
                                      .arg(currentStatus.absolutePosition.y)
                                      .arg(currentStatus.absolutePosition.z);


    QString strRelativePosition = QString("相对坐标: x: %1 | y: %2 | z: %3| 力矩: %4")
                                      .arg(currentStatus.relativePosition.x)
                                      .arg(currentStatus.relativePosition.y)
                                      .arg(currentStatus.relativePosition.z)
                                      .arg(currentStatus.torque);
    QString strWorkPosition = QString("工作坐标: x: %1 | y: %2 | z: %3")
                                  .arg(currentStatus.workPosition.x)
                                  .arg(currentStatus.workPosition.y)
                                  .arg(currentStatus.workPosition.z);
    QString strRemainingDistance = QString("剩余距离: x: %1 | y: %2 | z: %3")
                                       .arg(currentStatus.remainingDistance.x)
                                       .arg(currentStatus.remainingDistance.y)
                                       .arg(currentStatus.remainingDistance.z);
    ui->textAbsolutePosition->setText(strAbsolutePosition);
    ui->textRelativePosition->setText(strRelativePosition);
    ui->textWorkPosition->setText(strWorkPosition);
    ui->textRemainingDistance->setText(strRemainingDistance);

    m_databaseService->updateStatusTable(currentStatus);

    // 如果查询使能，重新启动定时器
    if (m_queryEnabled) {
        m_queryTimer->start(m_queryInterval);
    }
}

// 修改定时查询超时处理方法
void MainWindow::onQueryTimeout()
{
    if (m_queryEnabled && m_connected) {
        executeSingleQuery();
    }
}

// 在设备断开连接时自动停止查询
void MainWindow::setupDeviceConnections()
{
    // 连接设备通信服务信号
    connect(m_deviceCommService, &DeviceCommService::deviceConnected, this, [this]() {
        m_connected = true;
        updateFixtureControlState();
        updateParameterDisplay();
        on_btStartQuery_clicked();
    });

    connect(m_deviceCommService, &DeviceCommService::deviceDisconnected, this, [this]() {
        m_connected = false;
        // 更新夹具控制状态
        updateFixtureControlState();
        // 设备断开时自动停止查询
        if (m_queryEnabled) {
            stopPeriodicQuery();
            SysLogManager::logWarning(InfoType::DEVICE, "🔌 设备断开连接，已停止定时查询");
        }

        updateParameterDisplay();
    });

    connect(m_deviceCommService, &DeviceCommService::deviceErrorOccurred, this, [this](const QString& error) {
        // 发生错误时自动停止查询
        if (m_queryEnabled) {
            stopPeriodicQuery();
            SysLogManager::logError(InfoType::DEVICE, "🛑 设备错误，已停止定时查询");
        }
    });
}


void MainWindow::on_btStartQuery_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 设备未连接，无法操作查询");
        return;
    }

    if (!m_queryEnabled) {
        // 开始定时查询
        startPeriodicQuery();
    } else {
        // 停止定时查询
        stopPeriodicQuery();
    }
}

void MainWindow::on_btnSaveRate_clicked()
{
    saveParameters();
    SysLogManager::logSuccess(InfoType::SYSTEM, "工艺参数已保存到配置文件");

    // 同时发送到设备（如果已连接）
    if (m_connected) {
        QVariantMap recipeParams;
        recipeParams["FV"] = ui->lineEdit_RapidRate->text().toDouble();
        recipeParams["V"] = ui->lineEdit_FeedRate->text().toDouble();
        recipeParams["R"] = ui->lineEdit_SpindleSpeed->text().toDouble();
        DeviceController::instance()->sendCommand(DeviceProtocol::IPCCommand::SetupRecipe, recipeParams);
        SysLogManager::logSuccess(InfoType::DEVICE, "工艺参数已发送到设备");
    }
}



void MainWindow::on_btnStartSpindle_clicked()
{
    QVariantMap removeParams;
    removeParams["R"] = 2000;
    DeviceController::instance()->sendCommand(DeviceProtocol::IPCCommand::SpindleStart,removeParams);
}


void MainWindow::on_btnStopSpindle_clicked()
{
    DeviceController::instance()->sendCommand(DeviceProtocol::IPCCommand::SpindleStop);
}


// 在夹具操作按钮的槽函数中添加状态查询
void MainWindow::on_btnSetDO_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 设备未连接，无法执行夹紧操作");
        return;
    }

    int fixtureIndex = ui->comboBoxDO->currentIndex();
    if (fixtureIndex < 0) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 请先选择要操作的夹具");
        return;
    }

    int fixtureNumber = fixtureIndex + 1;
    quint32 ioBitsValue = 1 << (fixtureNumber - 1);

    QVariantMap params;
    params["IOBits"] = QString("%1").arg(ioBitsValue, 5, 16, QChar('0')).toUpper();

    SysLogManager::logInfo(InfoType::FIXTURE_CTRL, QString("🔧 夹紧夹具 %1 (IOBits: %2)").arg(fixtureNumber).arg(params["IOBits"].toString()));

    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::SetDO, params);

    m_deviceCommService->queryDIStatus();
}

void MainWindow::on_btnResetDO_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 设备未连接，无法执行松开操作");
        return;
    }

    int fixtureIndex = ui->comboBoxDO->currentIndex();
    if (fixtureIndex < 0) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 请先选择要操作的夹具");
        return;
    }

    int fixtureNumber = fixtureIndex + 1;
    quint32 ioBitsValue = 1 << (fixtureNumber - 1);

    QVariantMap params;
    params["IOBits"] = QString("%1").arg(ioBitsValue, 5, 16, QChar('0')).toUpper();

    SysLogManager::logInfo(InfoType::FIXTURE_CTRL, QString("🔧 松开夹具 %1 (IOBits: %2)").arg(fixtureNumber).arg(params["IOBits"].toString()));

    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::ResetDO, params);

    m_deviceCommService->queryDIStatus();

}

void MainWindow::on_btnReleaseAllFixture_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 设备未连接，无法执行全部松开操作");
        return;
    }

    SysLogManager::logInfo(InfoType::FIXTURE_CTRL, "🔧 执行全部松开操作");

    // 发送全部松开命令
    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::ReleaseAllFixture);
}

void MainWindow::on_btnClampAllFixture_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 设备未连接，无法执行全部夹紧操作");
        return;
    }

    SysLogManager::logInfo(InfoType::FIXTURE_CTRL, "🔧 执行全部夹紧操作");

    // 发送全部夹紧命令
    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::ClampAllFixture);
}

void MainWindow::updateFixtureControlState()
{
    bool enabled = m_connected;

    // 更新单个夹具控制按钮状态
    ui->btnSetDO->setEnabled(enabled);
    ui->btnResetDO->setEnabled(enabled);
    ui->comboBoxDO->setEnabled(enabled);

    // 更新批量控制按钮状态
    ui->btnReleaseAllFixture->setEnabled(enabled);
    ui->btnClampAllFixture->setEnabled(enabled);

    ui->btnLoadMaterial->setEnabled(enabled);
    ui->btnUnloadMaterial->setEnabled(enabled);

    // 根据状态设置按钮样式提示
    if (enabled) {
        ui->btnSetDO->setToolTip("夹紧选中的夹具");
        ui->btnResetDO->setToolTip("松开选中的夹具");
        ui->btnReleaseAllFixture->setToolTip("松开所有夹具");
        ui->btnClampAllFixture->setToolTip("夹紧所有夹具");
        ui->comboBoxDO->setToolTip("选择要操作的夹具");
    } else {
        ui->btnSetDO->setToolTip("设备未连接");
        ui->btnResetDO->setToolTip("设备未连接");
        ui->btnReleaseAllFixture->setToolTip("设备未连接");
        ui->btnClampAllFixture->setToolTip("设备未连接");
        ui->comboBoxDO->setToolTip("设备未连接");

        // 可选：设置禁用状态的样式
        QString disabledStyle = "QPushButton:disabled { background-color: #f0f0f0; color: #a0a0a0; }";
        ui->btnSetDO->setStyleSheet(disabledStyle);
        ui->btnResetDO->setStyleSheet(disabledStyle);
        ui->btnReleaseAllFixture->setStyleSheet(disabledStyle);
        ui->btnClampAllFixture->setStyleSheet(disabledStyle);
    }
}

void MainWindow::on_btnLoadMaterial_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 设备未连接，无法执行上料操作");
        return;
    }

    SysLogManager::logInfo(InfoType::FIXTURE_CTRL, "🔧 开始上料流程...");

    // 1. 检查夹具开合情况
    SysLogManager::logInfo(InfoType::FIXTURE_CTRL, "📋 检查夹具状态...");

    // 执行夹具状态查询
    m_deviceCommService->queryDIStatus();

    // 延迟等待状态更新
    QTimer::singleShot(500, this, [this]() {
        // 检查当前夹具状态
        StatusTable currentStatus;
        m_deviceCommService->getCurrentStatus(currentStatus);

        QString currentFixtureStatus = currentStatus.fixtureStatus;
        SysLogManager::logInfo(InfoType::FIXTURE_CTRL, QString("当前夹具状态: %1").arg(currentFixtureStatus));

        // 检查是否所有夹具都已经夹紧
        bool allClamped = isAllFixturesClamped(currentFixtureStatus);

        if (allClamped) {
            SysLogManager::logSuccess(InfoType::FIXTURE_CTRL, "✅ 所有夹具已经处于夹紧状态，无需重复操作");
            TaskManager::instance().completeTaskStatus(TaskType::LOAD_MATERIAL, true, "上料完成 - 夹具已夹紧");
            return;
        }

        // 2. 执行闭夹操作（夹紧所有夹具）
        SysLogManager::logInfo(InfoType::FIXTURE_CTRL, "🔧 执行闭夹操作...");
        m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::ClampAllFixture);

        // 再次查询确认状态
        QTimer::singleShot(500, this, [this]() {
            m_deviceCommService->queryDIStatus();
            SysLogManager::logSuccess(InfoType::FIXTURE_CTRL, "✅ 上料流程完成 - 夹具已夹紧");

            // 更新任务状态
            TaskManager::instance().completeTaskStatus(TaskType::LOAD_MATERIAL, true, "上料完成");
        });
    });
}

void MainWindow::on_btnUnloadMaterial_clicked()
{
    if (!m_connected) {
        SysLogManager::logError(InfoType::DEVICE, "❌ 设备未连接，无法执行下料操作");
        return;
    }

    SysLogManager::logInfo(InfoType::FIXTURE_CTRL, "🔧 开始下料流程...");

    // 1. 检查夹具松夹情况
    SysLogManager::logInfo(InfoType::FIXTURE_CTRL, "📋 检查夹具状态...");

    // 执行夹具状态查询
    m_deviceCommService->queryDIStatus();

    // 延迟等待状态更新
    QTimer::singleShot(500, this, [this]() {
        // 检查当前夹具状态
        StatusTable currentStatus;
        m_deviceCommService->getCurrentStatus(currentStatus);

        QString currentFixtureStatus = currentStatus.fixtureStatus;
        SysLogManager::logInfo(InfoType::FIXTURE_CTRL, QString("当前夹具状态: %1").arg(currentFixtureStatus));

        // 检查是否所有夹具都已经松开
        bool allReleased = isAllFixturesReleased(currentFixtureStatus);

        if (allReleased) {
            SysLogManager::logSuccess(InfoType::FIXTURE_CTRL, "✅ 所有夹具已经处于松开状态，无需重复操作");
            TaskManager::instance().completeTaskStatus(TaskType::UNLOAD_MATERIAL, true, "下料完成 - 夹具已松开");
            return;
        }

        // 2. 执行松夹操作（松开所有夹具）
        SysLogManager::logInfo(InfoType::FIXTURE_CTRL, "🔧 执行松夹操作...");
        m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::ReleaseAllFixture);

        // 再次查询确认状态
        QTimer::singleShot(500, this, [this]() {
            m_deviceCommService->queryDIStatus();
            SysLogManager::logSuccess(InfoType::FIXTURE_CTRL, "✅ 下料流程完成 - 夹具已松开");

            // 更新任务状态
            TaskManager::instance().completeTaskStatus(TaskType::UNLOAD_MATERIAL, true, "下料完成");
        });
    });
}

bool MainWindow::isAllFixturesClamped(const QString& fixtureStatus)
{
    if (fixtureStatus.isEmpty()) {
        return false;
    }

    bool ok;
    quint32 fixtureBits = fixtureStatus.toUInt(&ok, 16);
    if (!ok) {
        return false;
    }

    // 检查所有夹具位是否为0（夹紧状态）
    // 夹具位为0表示夹紧，为1表示松开
    return (fixtureBits & 0x0FFFF) == 0x00000;
}

bool MainWindow::isAllFixturesReleased(const QString& fixtureStatus)
{
    if (fixtureStatus.isEmpty()) {
        return false;
    }

    bool ok;
    quint32 fixtureBits = fixtureStatus.toUInt(&ok, 16);
    if (!ok) {
        return false;
    }

    // 检查所有夹具位是否为1（松开状态）
    // 夹具位为1表示松开，为0表示夹紧
    return (fixtureBits & 0x0FFFF) == 0x0FFFF;
}

void MainWindow::on_pushButton_clicked()
{
    QVariantMap params;
    params["IOBits"] = "10000";

    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::ResetDO, params);

    QVariantMap params1;
    params1["IOBits"] = "20000";

    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::ResetDO, params1);

    QVariantMap params2;
    params2["IOBits"] = "40000";

    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::ResetDO, params2);
}


void MainWindow::on_pushButton_2_clicked()
{
    QVariantMap params;
    params["IOBits"] = "10000";

    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::SetDO, params);

    QVariantMap params1;
    params1["IOBits"] = "20000";

    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::SetDO, params1);

    QVariantMap params2;
    params2["IOBits"] = "40000";

    m_deviceCommService->DeviceCommand(DeviceProtocol::IPCCommand::SetDO, params2);
}


void MainWindow::on_btnUpdateParameters_clicked()
{
    SysEnv& env = SysEnv::instance();
    // 加载配置
    env.load();
    loadDefaultParameters();

    // 同时发送到设备（如果已连接）
    if (m_connected) {
        QVariantMap recipeParams;
        recipeParams["FV"] = ui->lineEdit_RapidRate->text().toDouble();
        recipeParams["V"] = ui->lineEdit_FeedRate->text().toDouble();
        recipeParams["R"] = ui->lineEdit_SpindleSpeed->text().toDouble();
        DeviceController::instance()->sendCommand(DeviceProtocol::IPCCommand::SetupRecipe, recipeParams);
        SysLogManager::logSuccess(InfoType::DEVICE, "工艺参数已发送到设备");
    }


    TaskManager::instance().completeTaskStatus(TaskType::UPDATE_PARAMETERS,true,"参数更新完成");
}
